<template>
  <div class="style-container">
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="款式名称">
          <el-input v-model="queryParams.name" placeholder="请输入款式名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增款式</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <el-table :data="styleList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="款式名称" width="150"></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column label="缩略图" width="120">
          <template #default="scope">
            <el-image 
              style="width: 80px; height: 80px" 
              :src="scope.row.thumbnail" 
              fit="cover"
              :preview-src-list="[scope.row.thumbnail]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 1">
              删除
            </el-button>
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
              active-text="启用"
              inactive-text="禁用">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加或修改款式对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="styleFormRef" label-width="100px">
        <el-form-item label="款式名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入款式名称"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnail">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleThumbnailSuccess"
            :before-upload="beforeThumbnailUpload"
            :data="{
              module: 'style',
              relationId: form.id || 0
            }">
            <img v-if="form.thumbnail" :src="form.thumbnail" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详细图片" prop="images">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleImageSuccess"
            :data="{
              module: 'style-detail',
              relationId: form.id || 0
            }">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogImageVisible" title="预览">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: '',
})

// 表格数据
const styleList = ref([])
const total = ref(0)
const loading = ref(false)

// 分类选项
const categoryOptions = ref([
  { id: 1, name: '上衣' },
  { id: 2, name: '裤装' },
  { id: 3, name: '裙装' },
  { id: 4, name: '外套' },
  { id: 5, name: '套装' },
])

// 图片预览
const dialogImageUrl = ref('')
const dialogImageVisible = ref(false)

// 表单对话框
const dialog = reactive({
  title: '',
  visible: false,
})

// 表单数据
const styleFormRef = ref(null)
const form = reactive({
  id: undefined,
  name: '',
  categoryId: undefined,
  description: '',
  thumbnail: '',
  images: [],
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入款式名称', trigger: 'blur' },
    { min: 2, max: 50, message: '款式名称长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
  ],
  thumbnail: [
    { required: true, message: '请上传缩略图', trigger: 'change' }
  ]
}

// 上传相关
const uploadHeaders = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 获取款式列表
const getStyleList = () => {
  loading.value = true
  
  // 构建查询参数
  const params = new URLSearchParams();
  params.append('pageNum', queryParams.pageNum);
  params.append('pageSize', queryParams.pageSize);
  if (queryParams.name) params.append('name', queryParams.name);
  if (queryParams.status !== '') params.append('status', queryParams.status);
  
  // 调用后端API获取数据
  fetch(`/api/clothing/style/list?${params.toString()}`)
    .then(response => response.json())
    .then(res => {
      console.log('获取款式列表响应:', res);
      if (res && res.data) {
        styleList.value = res.data.records || [];
        total.value = res.data.total || 0;
      } else {
        ElMessage.error('获取数据失败: ' + (res.message || '未知错误'));
        styleList.value = [];
        total.value = 0;
      }
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败，请稍后重试');
      styleList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getStyleList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getStyleList()
}

// 分页页码改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getStyleList()
}

// 新增款式
const handleAdd = () => {
  dialog.title = '添加款式'
  dialog.visible = true
  Object.keys(form).forEach(key => {
    if (key !== 'status') {
      form[key] = key === 'images' ? [] : ''
    } else {
      form[key] = 1
    }
  })
  form.id = undefined
  
  // 表单清除验证
  if (styleFormRef.value) {
    styleFormRef.value.resetFields()
  }
}

// 编辑款式
const handleEdit = (row) => {
  dialog.title = '编辑款式'
  dialog.visible = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description,
    categoryId: row.categoryId,
    thumbnail: row.thumbnail,
    images: [], // 实际项目中需要从后端获取详细图片
    status: row.status
  })
  
  // 下一次DOM更新后重置表单验证
  setTimeout(() => {
    if (styleFormRef.value) {
      styleFormRef.value.clearValidate()
    }
  }, 0)
}

// 提交表单
const submitForm = () => {
  styleFormRef.value.validate((valid) => {
    if (valid) {
      const method = form.id ? 'PUT' : 'POST'
      const apiUrl = '/api/clothing/style'
      
      // 处理表单数据
      const formData = {
        ...form,
        // 确保只包含需要的字段
        name: form.name,
        categoryId: form.categoryId,
        description: form.description,
        thumbnail: form.thumbnail,
        status: form.status
      }
      
      // 如果是编辑模式，确保包含ID
      if (form.id) {
        formData.id = form.id
      }
      
      fetch(apiUrl, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        body: JSON.stringify(formData)
      })
        .then(response => response.json())
        .then(res => {
          if (res.success && res.code === 0) {
            ElMessage.success(form.id ? '更新成功' : '添加成功')
            dialog.visible = false
            getStyleList()
          } else {
            ElMessage.error((form.id ? '更新' : '添加') + '失败: ' + res.message)
          }
        })
        .catch(error => {
          console.error((form.id ? '更新' : '添加') + '失败:', error)
          ElMessage.error((form.id ? '更新' : '添加') + '失败，请稍后重试')
        })
    }
  })
}

// 删除款式
const handleDelete = (row) => {
  // 先检查状态
  if (row.status === 1) {
    ElMessage.warning('启用状态的款式不能删除，请先禁用');
    return;
  }

  ElMessageBox.confirm('确认要删除该款式吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除API
    fetch(`/api/clothing/style/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
      .then(response => response.json())
      .then(res => {
        console.log('删除款式响应:', res);
        if (res && res.code === 0) {
          ElMessage.success('删除成功');
          getStyleList();
        } else {
          ElMessage.error('删除失败: ' + (res.message || '未知错误'));
        }
      })
      .catch(error => {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      });
  }).catch(() => {
    // 取消删除，不做任何操作
  });
}

// 状态改变
const handleStatusChange = (row, status) => {
  const text = status === 1 ? '启用' : '禁用';
  
  fetch(`/api/clothing/style/status?id=${row.id}&status=${status}`, {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  })
    .then(response => response.json())
    .then(res => {
      console.log('更新状态响应:', res);
      if (res && res.data) {
        row.status = status;
        ElMessage.success(`已${text}`);
      } else {
        ElMessage.error(text + '失败: ' + (res.message || '未知错误'));
      }
    })
    .catch(error => {
      console.error(text + '失败:', error);
      ElMessage.error(text + '失败，请稍后重试');
    });
}

// 缩略图上传成功
const handleThumbnailSuccess = (res) => {
  console.log('缩略图上传成功，响应:', res);
  if (res && res.data) {
    form.thumbnail = res.data;
    ElMessage.success('缩略图上传成功');
  } else {
    ElMessage.error('缩略图上传失败: ' + (res.message || '未知错误'));
  }
}

// 缩略图上传前检查
const beforeThumbnailUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('只能上传JPG或PNG格式的图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
}

// 详细图片上传成功
const handleImageSuccess = (res) => {
  console.log('详细图片上传成功，响应:', res);
  if (res && res.data) {
    if (!form.images) {
      form.images = [];
    }
    form.images.push(res.data);
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败: ' + (res.message || '未知错误'));
  }
}

// 移除图片
const handleRemove = (file, fileList) => {
  // 实际项目中需要处理图片移除逻辑
  form.images = fileList.map(file => file.url || file.response.data)
}

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url || file.response.data
  dialogImageVisible.value = true
}

onMounted(() => {
  getStyleList()
})
</script>

<style scoped>
.style-container {
  padding: 20px;
}
.filter-container, .table-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style> 